import { createWebHistory, createRouter } from 'vue-router';
import Login from "../view/Login.vue";
import { useRoutesList } from "../stores/routesList.ts";
import { GetRouters } from "../api/common";
import NotFound from "../view/error/404.vue";
import NProgress from 'nprogress'   // 导入 nprogress
import 'nprogress/nprogress.css'   // 导入样式，否则看不到效果
NProgress.configure({ showSpinner: true })   // 显示右上角螺旋加载提示

// 添加类型声明
import type { RouteRecordRaw } from 'vue-router';
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
    { path: '/login', component: Login },
    { path:  '/:pathMatch(.*)*', component: NotFound },
    {
        path: '/',
        name: 'MainLayout',
        component: () => import('../layout/layout.vue'),
        redirect: '/home',
        children: []
    }
];

// 设置白名单
const whiteList = ["/login"];
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
});

// 路由守卫
router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    NProgress.start()
    const store = useRoutesList();
    //校验是否登录，如果没有登录直接到login页面
    if(localStorage.getItem("token") == null){
        if (to.path !== '/login') {
            next('/login')
        }
    }
    // 如果目标路径在白名单内，直接放行
    if (whiteList.includes(to.path)) {
        NProgress.done()
        next();
        return;
    }

    // 如果已经加载过动态路由，则无需再次加载
    if (store.routesList.length > 0) {
        NProgress.done()
        next();
        return;
    }
    try {
        // 从后端获取菜单数据
        const res = await  GetRouters();
        const menus=res.data
        if (menus.length===0){
            menus.push( {
                path: '/home',
                name: 'home',
                component:'dept/aaa',
                meta:{
                    title:'首页',
                    icon:'home',
                },
                children: []
            })
        }
        // 往store里面添加菜单信息
        await store.setRoutesList(menus);
        // 格式化菜单为Vue Router的路由配置
        const dynamicRoutes = formatRoutes(menus);
        // 添加动态路由到主布局组件下
        dynamicRoutes.forEach(route => {
            if (route.children && route.children.length>0) {
                // 对于有子路由的顶级路由，先添加顶级路由，再递归添加子路由
                router.addRoute('MainLayout', route);
                addChildrenRoutes(router, 'MainLayout', route);
            } else {
                router.addRoute('MainLayout', route);
            }
        });

        NProgress.done()
        // 重新导航到当前路径
        next({ ...to, replace: true });

    } catch (error) {
        console.error("加载动态路由失败:", error);
        NProgress.done()
        next({ path: '/login' }); // 如果加载失败，重定向到登录页或其他错误处理逻辑

    }
});
//获取全部路由地址
const modules = import.meta.glob('../view/**/*.vue')
const formatRoutes = (menu) => {
    return menu.map(item => {
        const route = {
            path: item.path,
            name: item.name,
            component: modules[`../view/${item.component}.vue`],
            meta: item.meta,
            children: []
        };
        if (item.children && item.children.length) {
            route.children = formatRoutes(item.children);
        }

        return route;
    });
};

const addChildrenRoutes = (router, parentName, parentRoute) => {
    parentRoute.children.forEach(childRoute => {
        router.addRoute(parentName, childRoute); // 将子路由添加到父级路由下
        if (childRoute.children && childRoute.children.length) {
            addChildrenRoutes(router, childRoute.name, childRoute); // 递归添加子路由
        }
    });
};

export default router;